#include "mainwindow.h"
#include "ui_mainwindow.h"

QSerialPort myserial;

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QObject::connect(&myserial,&QSerialPort::readyRead,this,&MainWindow::on_serial_receive_data);
    on_pushButtonScan_clicked();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_serial_receive_data()
{
    QByteArray dataArray;
    dataArray = myserial.readAll();//读取数据    

    if(Qt::Checked == ui->checkBoxHexRece->checkState())
    {
        if(!dataArray.isEmpty())
        {
            char *data = dataArray.data();
            while (*data)
            {
                 ui->textEditRece->insertPlainText(QString::number(*data, 16).toUpper() + " ");
                 data++;
            }

//            QString str;
//            str = dataArray.toHex();//把数据直接转化为16进制的字符串形式
//            ui->textEditRece->insertPlainText(str + " ");
        }
    }
    else
    {
        ui->textEditRece->insertPlainText(dataArray);
    }

    QTextCursor cursor=ui->textEditRece->textCursor();
    cursor.movePosition(QTextCursor::End); //保持编辑器在光标最后一行
    ui->textEditRece->setTextCursor(cursor);


}

void MainWindow::serial_ui_init()
{

}
void MainWindow::on_pushButtonScan_clicked()
{
    ui->comboBox_portName->clear();
    ui->textEditRece->append("共扫描到 "
                              + QString::number(QSerialPortInfo::availablePorts().count())
                              + " 个可用串口：");


    foreach( const QSerialPortInfo &Info,QSerialPortInfo::availablePorts())//读取串口信息
    {
        qDebug() << "portName    :"  << Info.portName();//调试时可以看的串口信息
        qDebug() << "Description   :" << Info.description();
        qDebug() << "Manufacturer:" << Info.manufacturer();

        ui->textEditRece->append(Info.portName() +"  "+ Info.description());
        QSerialPort serial;
        serial.setPort(Info);
        ui->comboBox_portName->addItem( Info.portName()  );//在comboBox那添加串口号
    }
}

void MainWindow::on_pushButtonOpenSerial_clicked()
{
    myserial.setPortName(ui->comboBox_portName->currentText());//combo中选定的串口号
    myserial.setBaudRate((ui->comboBoxBaud->currentText()).toInt());
    myserial.setDataBits((enum QSerialPort::DataBits)(ui->comboBoxDataBits->currentText().toInt()));
    switch(ui->comboBoxStopBits->currentText().toInt())
    {
        case 1: myserial.setStopBits(QSerialPort::OneStop);break;
        case 3: myserial.setStopBits(QSerialPort::OneAndHalfStop);break;
        case 2: myserial.setStopBits(QSerialPort::TwoStop);break;
        default:qDebug()<<"停止位错误"; return;
    }
    switch(ui->comboBoxParity->currentIndex())
    {
        case 0: myserial.setParity(QSerialPort::NoParity);break;
        case 1: myserial.setParity(QSerialPort::OddParity);break;
        case 2: myserial.setParity(QSerialPort::EvenParity);break;
        default:qDebug()<<"校验位错误"; return;
    }

    myserial.setFlowControl(QSerialPort::NoFlowControl);//流控制

    if( myserial.isOpen() )
        myserial.close();
    else
        myserial.open(QIODevice::ReadWrite);//打开串口

    if( myserial.isOpen() )
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_opened_icon"));
        ui->pushButtonOpenSerial->setText("关闭串口");
    }
    else
    {
        ui->pushButtonOpenSerial->setIcon(QIcon(":/image/serial_closed_icon"));
        ui->pushButtonOpenSerial->setText("打开串口");
    }

    if(myserial.error())
    {
        QMessageBox::information(this, tr("提示"), tr("操作失败，请重试或者重启本软件！"));
        qDebug()<<"串口打开失败，原因是："<<myserial.error();
        myserial.clearError();
    }
}

void MainWindow::on_pushButtonSend_clicked()
{
//    const char * str_data;
//    QByteArray ba = ui->lineEditSend->text().toLatin1(); // must
//    str_data = ba.data();
//    myserial.write(str_data);//发送
    if( myserial.isOpen() )
    {
        if(Qt::Checked == ui->checkBoxHexSend->checkState())
        {

        }
        else
        {
            myserial.write(ui->lineEditSend->text().toUtf8());//字符发送
        }
    }
    else
    {
        ui->textEditRece->append("串口未打开！");
    }

}

void MainWindow::on_pushButton_clicked()
{
    ui->textEditRece->setText("");
}
